package com.fang.api.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.http.client.HttpClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

@Configuration
public class RestAutoConfig {

    public static class RestTemplateConfig {


        /**
         * Loadbalance spring 对restTemplate bean进行定制
         */
        @Bean
        @LoadBalanced
        RestTemplate lbRestTemplate(HttpClient httpClient) {
            RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
            template.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("utf-8"))); // 传输数据的时候保持中文的utf-8编码
            template.getMessageConverters().add(1, new FastJsonHttpMessageConverter());//反序列化
            return template;
        }
    }
}
